<?php

/**
 * 仓库货位列表ajax类
 * @package  ajax
 * @subpackage  backend
 * @create by allen.qiang
 */
quanli_require('module/base/wmsHandler.class.php');

class ajax_storeShelf {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 7: //仓库库位列表
                    $this->storeShelfList();
                    break;

                case 8: //仓库库位添加或编辑
                    $this->storeShelfAdd();
                    break;

                case 9: //删除仓库货位
                    $this->storeShelfDelete();
                    break;

                case 10: //批量添加货位
                    $this->batchShelf();
                    break;

            }

        }

    }

    //仓库库位列表
    function storeShelfList(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeID     = isset($_REQUEST['storeID']) && $_REQUEST['storeID'] != -1  ? $_REQUEST['storeID'] : null;
        $shelf_name  = trim($_REQUEST['shelf_name']);
        $page        = $_REQUEST['page'];
        $rp          = $_REQUEST['rp'];

        //组装查询条件数组
        $search_arr = array();

        //查询条件类型
        $search_type = '';

        //查询SQL
        $search_string = '';

        if( !empty( $storeID ) ){
            $search_string .= ' AND wss.storeID=?';
            $search_type   .= 'i';
            $search_arr[] = $storeID;
        }

        if( !empty( $shelf_name ) ){
            $search_string .= ' AND wss.shelf_name like ?';
            $search_type   .= 's';
            $search_arr[] = '%'.$shelf_name.'%';
        }

        if( $search_string ){
            $search_string = ' WHERE ' . substr( $search_string , 4 );
        }

        try {

            //排序
            $sql_sequee = sprintf(" ORDER BY %s %s ",$_REQUEST['sortname'],$_REQUEST['sortorder']);

            //分页
            $limit =  $sql_sequee . ' LIMIT ' . ($page-1)*$rp . ',' . $rp;

            //查询总数
            $sqlcount = "SELECT count(*) num FROM wms_store_shelf wss INNER JOIN wms_store ws ON wss.storeID = ws.storeID " . $search_string;
            $sqlcount_result = $G_PGLOB->DBCA->stmt_query($sqlcount,$search_type,$search_arr);

            //查询数据
            $sql = 'SELECT ws.storeID,ws.storeName,wss.shelfID,wss.shelf_name
                  FROM wms_store_shelf wss INNER JOIN wms_store ws ON wss.storeID = ws.storeID ' . $search_string . $limit;
            $result  =  $G_PGLOB->DBCA->stmt_query($sql,$search_type,$search_arr);

            //组织返回的数据
            $result_array = array(
                'page'  => $_REQUEST['page'],
                'total' => $sqlcount_result[0]->num,
                'rows'  => array()
            );

            if( $result ){

                foreach ( $result as $key=>$value){

                    if( $G_PGLOB->has_permission(6010) ){

                        $result_array['rows'][$key] = array(
                            'id' => $value->storeID."_".$value->shelfID,
                            'cell' => array(
                                '<a href="javascript: void(0);" onclick="storeShelf.edit(' . $value->storeID . ',' . $value->shelfID .');" >修改</a>',
                                $value->storeName,
                                $value->shelf_name
                            )
                        );

                    } else {

                        $result_array['rows'][$key] = array(
                            'id' => $value->storeID."_".$value->shelfID,
                            'cell' => array(
                                $value->storeName,
                                $value->shelfID,
                                $value->shelf_name
                            )
                        );

                    }


                }


            }

            echo json_encode($result_array);
            return;
        }catch(Exception $e){
            error_log($e->getMessage());
            echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
            return;
        }

    }

    //编辑或添加货位
    function storeShelfAdd(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeID = $_REQUEST['storeID'];
        $shelfID = $_REQUEST['shelfID'];

        //查询仓库信息
        $storeArr = array('storeID'=>$storeID);
        $storeInfo = $commHandler->search($storeArr,'wms_store');

        if( empty($storeInfo) ){
            echo json_encode( array('message'=>'没有找到对应仓库信息' , 'code'=>404 ) );
            return;
        }

        //校验该库位号在此仓库中是否已存在
        $checkShelfObj = new entity('wms_store_shelf');
        $checkShelfObj->storeID    = $storeID;
        $checkShelfObj->shelf_name = $_REQUEST['shelf_name'];

        if( $shelfID ){

            if( $G_PGLOB->DBCA->fetch($checkShelfObj) ){

                if(  $checkShelfObj->shelfID != $shelfID ){
                    echo json_encode( array('message'=>'该货位号['.$_REQUEST['shelf_name'].']已存在','code'=>400) );
                    return;
                }

            }

        }else{

            if( $G_PGLOB->DBCA->fetch($checkShelfObj) ){
                echo json_encode( array('message'=>'该货位号['.$_REQUEST['shelf_name'].']已存在','code'=>400) );
                return;
            }

        }

        $storeShelfObj = new entity('wms_store_shelf');
        $storeShelfObj->storeID = $storeID;
        $storeShelfObj->shelfID = $shelfID;

        if( !empty($shelfID) ){

            if(!$G_PGLOB->DBCA->fetch($storeShelfObj)){
                echo json_encode( array('message'=>'没有找到该货位信息','code'=>404) );
                return;
            }

        }

        $storeShelfObj->shelf_name = $_REQUEST['shelf_name'];


        try{

            $G_PGLOB->DBCA->save($storeShelfObj);

            if( !empty($shelfID) ){
                echo json_encode( array('message'=>'编辑成功','code'=>200) );
            }else{
                echo json_encode( array('message'=>'保存成功','code'=>200) );
            }

            return;

        }catch(Exception $e){
            error_log($e->getMessage());
            echo json_encode( array('message'=>'保存成功','code'=>200) );
            return;
        }

    }

    /**
     * 删除货位
     * $_POST['store_array']  = array(
    key => array (storeID,shelfID)
     *          ...
     * )
     */
    function storeShelfDelete(){

        global $G_PGLOB;

        if(!isset($_REQUEST['store_array']) || empty($_REQUEST['store_array']) ){
            die( json_encode( array('code'=>400 , 'message' => '请选择要删除的货位') ) );
        }

        $wms_store_shelf_obj = array();     //货位表数据
        foreach ($_REQUEST['store_array'] as $value){
            $wms_store_shelf = new entity('wms_store_shelf');
            $wms_store_shelf->storeID = $value[0];
            $wms_store_shelf->shelfID = $value[1];
            if(!$G_PGLOB->DBCA->fetch($wms_store_shelf)){
                die( json_encode( array('code' => 404 ,'message' => sprintf("编号[%d]的货位已不存在，请刷新页面",$value[1])) ) );
            }
            $wms_store_shelf_obj[] = $wms_store_shelf;
        }

        $sql = "DELETE FROM wms_store_shelf_goods WHERE storeID = ? AND shelfID = ?";

        try{

            $G_PGLOB->DBCA->beginTransaction();

            foreach ($wms_store_shelf_obj as $obj){
                //删除货位与商品映射
                $G_PGLOB->DBCA->stmt_query($sql,'ii',$obj->storeID,$obj->shelfID);

                //删除货位
                $G_PGLOB->DBCA->delete($obj);
            }

            $G_PGLOB->DBCA->commit();
            echo json_encode(array('code' => 200 , 'message' => '删除成功'));
        }catch (Exception $e){
            $G_PGLOB->DBCA->rollBack();
            error_log($e->getMessage());
            echo json_encode(array('code' => 500 , 'message' => '系统错误，删除失败'));
        }
        return;
    }

    //批量生产库位号
    private function batchShelf(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        //接收参数
        $storeID = $_REQUEST['storeID'];  //仓库ID
        $prefix = $_REQUEST['prefix'];  //前缀
        $suffix = $_REQUEST['suffix'];  //后缀
        $number = $_REQUEST['number'];  //数量

        //查询仓库信息
        $storeArr = array('storeID'=>$storeID);
        $storeInfo = $commHandler->search($storeArr,'wms_store');

        if( empty($storeInfo) ){
            echo json_encode( array('message'=>'没有找到对应仓库信息' , 'code'=>404 ) );
            return;
        }

        if( $number == 0 ){
            echo json_encode( array('message'=>'请输入大于0的正整数' , 'code'=>400 ) );
            return;
        }

        //保存对象数组
        $params = array();

        for( $i=1; $i<=$number; $i++ ){

            $wms_shelf = new entity('wms_store_shelf');
            $wms_shelf->storeID    = $storeID;
            $wms_shelf->shelf_name = $prefix . $i . $suffix;

            if( $G_PGLOB->DBCA->fetch($wms_shelf) ){
                continue;
            }

            $params[] = $wms_shelf;

        }

        try{

            if( $params ){

                //开启事务
                $G_PGLOB->DBCA->beginTransaction();

                foreach( $params as $obj ){
                    $G_PGLOB->DBCA->save( $obj );
                }

                //提交事务
                $G_PGLOB->DBCA->commit();

            }

            echo json_encode( array('message'=>'批量生成库位号成功' , 'code'=>200 ) );
            return;

        }catch(Exception $e){

            if( $params ){
                //回滚事务
                $G_PGLOB->DBCA->rollBack();
            }
            error_log( $e->getMessage() );
            echo json_encode( array('message'=>'系统错误，批量生产库位号失败' , 'code'=>500 ) );
            return;

        }

    }

}